package com.example.huilv.service;


import com.example.huilv.model.LearnUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

//标记为 service
@Service
public class LoginService {


    private JdbcTemplate jdbcTemplate;


    @Autowired
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    /**
     * 登录
     * @param username 用户名
     * @param password 密码
     * @return 昵称
     */
    public String login(String username, String password){
        //校验 username 和 password
        //读取数据库
        String sql =
                "SELECT * FROM `learn_bank` WHERE username = "
                        +
                "'"
                + username +
                "'";

        //例子1  username= dam
        //sql = "SELECT * FROM `learn_bank` WHERE username = 'dam'";
        //例子2  username= wyx
        //sql = "SELECT * FROM `learn_bank` WHERE username = 'wyx'";
        //链接JDBC
        List<LearnUser>  list= jdbcTemplate.query(sql, new BeanPropertyRowMapper(LearnUser.class));
        if (list.isEmpty()) {
            return "login fail user not found";
        }
        //校验密码
        LearnUser learnUser = list.get(0);
        if (!learnUser.getPassword().equals(password)) {
            return "login fail password error";
        }
        return learnUser.getNickName();
    }
}
